package com.evildog.workspace.auth.controller;


import com.evildog.workspace.auth.enums.AuthCustomExceptionDesc;
import com.evildog.workspace.auth.grant.GrantFactory;
import com.evildog.workspace.auth.grant.GrantParameter;
import com.evildog.workspace.auth.grant.Granter;
import com.evildog.workspace.auth.vo.AuthVO;
import com.evildog.workspace.common.exception.BadRequestException;
import com.evildog.workspace.common.result.Result;
import com.evildog.workspace.common.result.ResultGenerator;
import com.evildog.workspace.security.jwt.core.Token;
import com.evildog.workspace.security.jwt.core.TokenUserInfo;
import com.evildog.workspace.security.jwt.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/")
@Api("授权接口")
@AllArgsConstructor
public class AuthController {

    private final JwtUtil jwtUtil;

    /**
     * 备用get方法，便于直接链接请求token接口
     * <p>
     * 获取认证token
     */
    @GetMapping("/token")
    @ApiOperation(value = "get 获取认证token")
    public Result<AuthVO> getToken(@Validated GrantParameter parameter) {
        return getAuth(parameter);
    }

    @PostMapping("/token")
    @ApiOperation(value = "post 获取认证token")
    public Result<AuthVO> postToken(@Validated @RequestBody GrantParameter parameter) {
        return getAuth(parameter);
    }

    private Result<AuthVO> getAuth(GrantParameter parameter) {
        Granter granter = GrantFactory.getGranter(parameter.getGrantType());

        TokenUserInfo tokenUserInfo = granter.grant(parameter);
        if (tokenUserInfo == null) {
            throw new BadRequestException(AuthCustomExceptionDesc.USER_NOT_FOUND);
        }

        Token accessToken = jwtUtil.createAccessTokenByUserInfo(tokenUserInfo);
        Token refreshToken = jwtUtil.createRefreshTokenByUserInfo(tokenUserInfo);
        AuthVO authVO = new AuthVO()
                .setAvatar(tokenUserInfo.getAvatar())
                .setNickname(tokenUserInfo.getNickname())
                .setAccessToken(accessToken.getToken())
                .setAccessTokenExpire(accessToken.getExpireSecond())
                .setRefreshToken(refreshToken.getToken())
                .setRefreshTokenExpire(refreshToken.getExpireSecond())
                ;

        return ResultGenerator.success(authVO);

    }


}
